﻿using GN.Pay.Client.Utils;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace GN.Pay.Client.Commands
{
    class ServiceCommand : ACommand
    {
        public override string CommandCode
        {
            get
            {
                return "call";
            }
        }

        public override string CommandHelpExplain
        {
            get
            {
                return "调用服务";
            }
        }

        public override void SendCommand(string args)
        {
            if (!ConfigureCommand.currentConfigure.IsConfig())
            {
                throw new Exception("未配置服务，请先调用 config 命令进行配置");
            }
            if (string.IsNullOrWhiteSpace(args))
            {
                throw new Exception("至少需要服务名参数");
            }
            int index = args.IndexOf(" ");
            string serviceName;
            string jsonParams = null;
            if (index <= 0)
            {
                serviceName = args;
                jsonParams = "";
            }
            else
            {
                serviceName = args.Substring(0, index);
                if (args.Length > index)
                {
                    jsonParams = args.Substring(index).Trim();
                }
            }
            var client = ServiceUtils.CreateServiceClient(ConfigureCommand.currentConfigure);
            Stopwatch st = new Stopwatch();
            st.Start();
            try
            {
                var re = client.CommandRequest(serviceName, jsonParams);
                Console.WriteLine("Result:");
                if (re != null)
                {
                    Console.WriteLine(re.ToString(Newtonsoft.Json.Formatting.Indented));
                }
                else
                {
                    Console.WriteLine("None");
                }               
            }
            finally
            {
                Console.WriteLine("Time : " + st.ElapsedMilliseconds + " ms");
                st.Stop();
                st = null;
            }
        }
    }
}
